package com.zlm.user.emp.service.impl;

import com.zlm.amqp.conf.RabbitConfig;
import com.zlm.common.base.AbstractBaseService;
import com.zlm.common.base.PageEntity;
import com.zlm.common.constants.*;
import com.zlm.common.dto.CoordinatesDto;
import com.zlm.common.dto.HxUserDto;
import com.zlm.common.dto.QqResponseDto;
import com.zlm.common.dto.baidurequest.BaiduResultDto;
import com.zlm.common.dto.userEmp.EmpInfoParamsDto;
import com.zlm.common.dto.WechatResultDto;
import com.zlm.common.entity.UserIdImgDO;
import com.zlm.common.enums.*;
import com.zlm.common.util.*;
import com.zlm.huanxin.util.HuanxinUtils;
import com.zlm.user.emp.dao.SysEmpDao;
import com.zlm.user.emp.dao.UserIdImgDao;
import com.zlm.user.emp.entity.SysEmpDO;
import com.zlm.user.emp.dao.UserTokenDao;
import com.zlm.common.entity.UserTokenDO;
import com.zlm.common.dto.userEmp.SysEmpDto;
import com.zlm.user.emp.service.SysEmpService;
import com.zlm.user.emp.util.EmpUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务实现类
 * @Author: duyufu
 * @Date: 2019/3/29 11:06
 */
@Service
public class SysEmpServiceImpl extends AbstractBaseService<SysEmpDao, SysEmpDO> implements SysEmpService {

    @Autowired
    private UserTokenDao userTokenDao;
    @Autowired
    private UserIdImgDao userIdImgDao;

    @Autowired
    @Override
    public void setBaseDao(SysEmpDao sysEmpDao) {
        this.baseDao = sysEmpDao;
    }

    @Override
    public SysEmpDto queryEmpByMobileAndPassword(String mobile, String password) {
        password = MD5Utils.getStringMD5(password);
        SysEmpDto sysEmpDto = baseDao.queryEmpByMobileAndPassword(mobile,password);
        return sysEmpDto;
    }

    @Override
    public boolean isExistMobile(String mobile) {
        int m = baseDao.isExistEmp(mobile);
        if (m>0){
            return true;
        }
        return false;
    }



    /**
     * 根据手机号修改密码
     * @param mobile
     * @param password
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updatePassword(String mobile, String password) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("mobile",mobile);
        map.put("userPwd", MD5Utils.getStringMD5(password));
        return baseDao.updatePassword(map);

    }

    /**
     * 微信注册用户
     * @param userInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer wechatRegisterEmp(WechatResultDto userInfo) {
        SysEmpDO newEmp = new SysEmpDO();
        newEmp.setEmpName(userInfo.getNickname());
        newEmp.setSex(userInfo.getSex());
        newEmp.setCity(userInfo.getCity());
        newEmp.setProvince(userInfo.getProvince());
        newEmp.setAlive(1);
        newEmp.setWechatOpenid(userInfo.getOpenid());
        newEmp.setStatus(VerifyStatusEnum.STATUS_100.getCode());
        Integer empId = baseDao.insertEmp(newEmp);
//        String username = UserConstants.USER_TYPE_EMP_STRING.concat(empId.toString());
//        String queueName = RabbitConfig.HX_EMP_REGISTER;
        //环信注册
//        HuanxinUtils.huanxinRegister(empId,username,queueName);
        return empId;
    }

    /**
     * 根据openid获取用户
     * @param emp
     * @return
     */
    @Override
    public SysEmpDto queryEmp(SysEmpDO emp) {
        SysEmpDto user = baseDao.selectEmp(emp);
        return user;
    }

    /**
     * QQ注册用户
     * @param userInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer qqRegisterEmp(QqResponseDto userInfo) {
        SysEmpDO newEmp = new SysEmpDO();
        newEmp.setEmpName(userInfo.getNickname());
        newEmp.setSex(SexEnum.getCodeByName(userInfo.getGender()));
        newEmp.setProvince(userInfo.getProvince());
        newEmp.setCity(userInfo.getCity());
        newEmp.setAlive(1);
        newEmp.setQqOpenid(userInfo.getOpenid());
        newEmp.setAvatar(userInfo.getFigureurlQq1());
        newEmp.setStatus(VerifyStatusEnum.STATUS_100.getCode());
        Integer empId = baseDao.insertEmp(newEmp);
//        String username = UserConstants.USER_TYPE_EMP_STRING.concat(empId.toString());
//        String queueName = RabbitConfig.HX_EMP_REGISTER;
        //环信注册
//        HuanxinUtils.huanxinRegister(empId,username,queueName);
        return empId;
    }

    @Override
    public SysEmpDto queryEmpById(Integer empId) {
        SysEmpDto empDto = baseDao.queryEmpById(empId);
        empDto.setEmpName(empDto.getEmpName() == null ? UserConstants.USER_DEFAULT_NAME : empDto.getEmpName());
        empDto.setAvatar(empDto.getAvatar() == null ? "" : CommonConstants.IMG_URL.concat(empDto.getAvatar()));
        empDto.setSexName(empDto.getSex() == null ? "" : SexEnum.getNameByCode(empDto.getSex()));
        empDto.setMarriedName(empDto.getMarried() == null ? "" : MarriedEnum.getNameByCode(empDto.getMarried()));
        empDto.setIsWorkName(empDto.getIsWork() == null ? "" : JobHuntingStatusEnum.getNameByCode(empDto.getIsWork()));
        empDto.setEducationName(empDto.getEducation() == null ? "" : EducationEnum.getNameByCode(empDto.getEducation()));
        return empDto;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveEmpInfo(EmpInfoParamsDto empInfoParamsDto) {
        SysEmpDto empDto = baseDao.queryEmpById(empInfoParamsDto.getEmpId());
        if (StringUtils.isNotBlank(empDto.getAvatar()) && StringUtils.isNotBlank(empInfoParamsDto.getAvatar()) && !empInfoParamsDto.getAvatar().equals(empDto.getAvatar()) ) {
            //保存新图片路径，删除文件
            baseDao.saveEmpInfo(empInfoParamsDto);
            String filePath = CommonConstants.IMG_URL.concat(empInfoParamsDto.getAvatar());
            File deleteFile = new File(filePath);
            if (!deleteFile.exists()) {

            }else {
                deleteFile.delete();
            }
        }else {
            baseDao.saveEmpInfo(empInfoParamsDto);
        }
        EmpUtils.updateEmpPerfect(empInfoParamsDto.getEmpId());
    }

    @Override
    public String queryEmpPassword(Integer empId) {
        return baseDao.queryEmpPassword(empId);
    }

    @Override
    public void updatePasswordByEmpId(Integer empId,String password) {
        baseDao.updatePasswordByEmpId(empId,password);
    }

    @Override
    public SysEmpDO queryEmpByIdNo(String idNo) {
        return baseDao.queryEmpByIdNo(idNo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void realNameAuthentication(Map<String, Object> empInfo) {
        Integer sex = (Integer) empInfo.get("sex");
        String birthday = (String) empInfo.get("birthday");
        Integer age = (Integer) empInfo.get("age");
        Integer empId = (Integer) empInfo.get("empId");
        String realName = (String) empInfo.get("realName");
        String idNo = (String) empInfo.get("idNo");
        String idcardFront = (String) empInfo.get("idcardFront");
        String idcardBehind = (String) empInfo.get("idcardBehind");
        //保存用户身份证信息
        UserIdImgDO idFront = new UserIdImgDO();
        idFront.setEmpId(empId);
        idFront.setIsback(UserConstants.USER_IMG_TYPE0);
        idFront.setImgSrc(idcardFront);
        idFront.setCreateUser(empId);
        idFront.setLastModifyUser(empId);
        idFront.setIdentitys(UserConstants.USER_TYPE_EMP);
        UserIdImgDO idBehind = new UserIdImgDO();
        idBehind.setEmpId(empId);
        idBehind.setIsback(UserConstants.USER_IMG_TYPE1);
        idBehind.setImgSrc(idcardBehind);
        idBehind.setCreateUser(empId);
        idBehind.setLastModifyUser(empId);
        idBehind.setIdentitys(UserConstants.USER_TYPE_EMP);
        List<UserIdImgDO> idImgList = new ArrayList<>(2);
        idImgList.add(idFront);
        idImgList.add(idBehind);
        userIdImgDao.saveIdImg(idImgList);
        //修改用户信息
        SysEmpDO emp = new SysEmpDO();
        emp.setEmpId(empId);
        emp.setSex(sex);
        emp.setBirthday(DateTimeUtils.string1Date(birthday));
        emp.setEmpName(realName);
        emp.setCreateUser(realName);
        emp.setLastModifyUser(realName);
        emp.setIdNo(idNo);
        emp.setIdNoStatus(UserConstants.USER_ACTIVATION_STATUS_WAIT);
        baseDao.update(emp);

    }

    @Override
    public int countEmpByIdNo(String idNo) {
        return baseDao.countEmpByIdNo(idNo);
    }

    @Override
    public void updateHxPasswordByEmpId(Integer empId,String hxID, String hxPassword) {
        baseDao.updateHxPasswordByEmpId(empId,hxID,hxPassword);
    }

    @Override
    public List<HxUserDto> searchFriend(String keyword) {
        return baseDao.searchFriend(keyword);
    }

    @Override
    public HxUserDto queryHxUser(String hxId) {
        return baseDao.queryHxUser(hxId);
    }

    @Override
    public PageEntity queryLocalEmp(Integer pageNumber, Integer pageSize, CoordinatesDto coordinates) {
        String city = getCity(coordinates);
        Integer count = baseDao.queryCountLocalEmp(city);
        PageEntity pageEntity = setPage(pageNumber, pageSize);
        List<SysEmpDto> empDtoList = baseDao.queryLocalEmp(pageEntity.getPageNumber(),pageEntity.getPageSize(),city);
        PageEntity page = getPage(pageEntity,count,empDtoList);
        return page;
    }

    /**
     * 保存token
     * @param mobile
     * @param empId
     * @return
     */
    private UserTokenDO saveToken(String mobile,Integer empId) {
        String newToken = UuidUtils.get32UUID();
        UserTokenDO userToken = new UserTokenDO();
        userToken.setUserId(empId);
        userToken.setToken(newToken);
        userToken.setMobile(mobile);
        userToken.setUserType(UserConstants.USER_TYPE_EMP);
        userToken.setAlive(1);
        int token = userTokenDao.getEmpToken(mobile);
        if (token==0){
            userTokenDao.saveUserToken(userToken);
        } else {
            userTokenDao.updateUserToken(userToken);
        }
        return userToken;
    }

    /**
     * 补全用户信息
     * @param user
     * @return
     */
    private SysEmpDto completEmpDto(SysEmpDto user) {
        if (StringUtils.isBlank(user.getEmpName())) {
            user.setEmpName(UserConstants.USER_DEFAULT_NAME);
        }
        if (null != user.getSex()) {
            user.setSexName(SexEnum.getNameByCode(user.getSex()));
        }
        if (null != user.getMarried()) {
            user.setMarriedName(MarriedEnum.getNameByCode(user.getMarried()));
        }
        if (null != user.getStatus()) {
            user.setStatusName(VerifyStatusEnum.getNameByCode(user.getStatus()));
        }
        if (StringUtils.isNotBlank(user.getIdNo())) {
            user.setAge(IDCardUtils.getAgeByIdNo(user.getIdNo()));
        }
        if (StringUtils.isBlank(user.getEmpName())) {
            user.setEmpName(UserConstants.USER_DEFAULT_NAME);
        }
        return user;
    }
}
